import { createRouter, createWebHashHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'Home',
    // webpackChunkName为进入那个页面就加载那个页面，而不是全部加载
    component: () => import(/* webpackChunkName: "Home" */ '../views/home/Home')
  },
  {
    // 后面要跟一个数字才满足路由跳转的要求
    path: '/shop/:id', // 配合router-link :to="`/shop/${item._id}`"
    name: 'Shop',
    component: () => import(/* webpackChunkName: "Shop" */ '../views/shop/Shop')
  },
  {
    path: '/cartList',
    name: 'CartList',
    component: () =>
      import(/* webpackChunkName: "CartList" */ '../views/cartList/CartList')
  },
  {
    path: '/orderConfirmation/:id/:addressId?',
    name: 'OrderConfirmation',
    component: () =>
      import(
        /* webpackChunkName: "orderConfirmation" */ '../views/orderConfirmation/OrderConfirmation'
      )
  },
  {
    path: '/orderList',
    name: 'OrderList',
    component: () =>
      import(/* webpackChunkName: "OrderList" */ '../views/orderList/OrderList')
  },
  {
    path: '/person',
    name: 'PersonalInfo',
    component: () =>
      import(
        /* webpackChunkName: "person" */ '../views/personalInfo/PersonalInfo'
      )
  },
  {
    path: '/register',
    name: 'Register',
    component: () =>
      import(/* webpackChunkName: "register" */ '../views/register/Register'),
    beforeEnter(to, from, next) {
      const { isLogin } = localStorage
      isLogin ? next({ name: 'Home' }) : next()
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () =>
      import(/* webpackChunkName: "login" */ '../views/login/Login'),
    beforeEnter(to, from, next) {
      const { isLogin } = localStorage
      isLogin ? next({ name: 'Home' }) : next()
    }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
router.beforeEach((to, from, next) => {
  const { isLogin } = localStorage
  const { name } = to
  const isLoginOrRegister = name === 'Login' || name === 'Register'
  isLogin || isLoginOrRegister ? next() : next({ name: 'Login' })
})
export default router
